
package com.joysuch.wwyt.dataimport.util;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;

public class DataImportUtils {

    public static <T> List<T> parseData(InputStream inputStream, int sheetIndex, int startRow, Class<T> clazz,
            boolean trimStringData) throws IOException, Exception {
        ImportParams params = new ImportParams();
        params.setStartSheetIndex(sheetIndex);
        params.setHeadRows(startRow);
        return getResultList(inputStream, clazz, trimStringData, params);
    }

    public static <T> List<T> parseData(InputStream inputStream, ImportParams params, Class<T> clazz,
                                        boolean trimStringData) throws Exception {
        return getResultList(inputStream, clazz, trimStringData, params);
    }

    private static <T> List<T> getResultList(InputStream inputStream, Class<T> clazz, boolean trimStringData, ImportParams params) throws Exception {
        List<T> result = ExcelImportUtil.importExcel(inputStream, clazz, params);
        int index = 1;
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(clazz, "rowIndex");
        if (propertyDescriptor != null && propertyDescriptor.getWriteMethod() != null) {
            for (T b : result) {
                propertyDescriptor.getWriteMethod().invoke(b, params.getStartRows() + index);
                index++;
            }
        }
        if (trimStringData) {
            for (T b : result) {
                trimData(b);
            }
        }
        return result;
    }


    /**
     * 读取类的所有属性，将String类型数据trim后设置回去
     * 
     * @param rb
     */
    public static void trimData(Object rb) {
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(rb.getClass());
        for (PropertyDescriptor pd : descriptors) {
            if (pd.getPropertyType() == String.class && pd.getWriteMethod() != null && pd.getReadMethod() != null) {
                try {
                    String value = (String) pd.getReadMethod().invoke(rb, null);
                    if (value != null) {
                        value = value.trim();
                        pd.getWriteMethod().invoke(rb, value);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
